<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    title="授权数据权限"
    width="50%"
    showFooter
    @ok="handleSubmitRules"
  >
    <div style="display: flex; width: 100%">
      <BasicTree
        ref="grantTree"
        style="width: 300px"
        v-model:value="roleMenus"
        :treeData="treeData"
        :fieldNames="{ title: 'title', key: 'id' }"
        checkStrictly
        toolbar
        @select="selectNode"
        title="角色权限"
      />
      <div style="flex: 1">
        <BasicTree
          ref="ruleTree"
          style="width: 300px"
          v-model:value="userRule"
          :treeData="ruleData"
          :fieldNames="{ title: 'ruleName', key: 'id' }"
          checkStrictly
          checkable
          toolbar
          title="菜单数据权限"
        />
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicTree, TreeActionType, TreeItem } from '@/components/Tree';
import { list } from '@/api/sys/sysDataScopeManage';
import { useMessage } from '@/hooks/web/useMessage';
import { getMenuList, grantRule, listRules } from '@/api/sys/system';
const emit = defineEmits(['success', 'register']);
const { createMessage } = useMessage();
const treeData = ref<TreeItem[]>([]);
const roleMenus = ref([]);

const userRule = ref([]);
const ruleData = ref([]);
const ruleTree = ref();
const roleData = ref();
const selectMenu = ref('');
const [registerDrawer, { setDrawerProps, changeLoading }] = useDrawerInner(
  async (data) => {
    setDrawerProps({ confirmLoading: false });
    treeData.value = (await getMenuList()) as any as TreeItem[];
    setTimeout(() => {
      grantTree.value?.expandAll(true);
    });
    roleData.value = { ...data.record };
    roleMenus.value = roleData.value.grantMenuIdList?.split(',');
  }
);

async function selectNode(node: TreeItem) {
  if (node.length) {
    const data = await list({ menuId: node[0] });
    ruleData.value = data;
    const roleRules = await listRules({
      menuId: node[0],
      roleId: roleData.value.id,
    });
    ruleTree.value.setCheckedKeys(roleRules);
    selectMenu.value = node[0];
  } else {
    ruleData.value = [];
    selectMenu.value = '';
  }
}
const grantTree = ref<Nullable<TreeActionType>>(null);
async function handleSubmitRules() {
  changeLoading(true);
  try {
    const { checked } = ruleTree.value.getCheckedKeys();
    await grantRule({
      roleId: roleData.value.id,
      menuId: selectMenu.value,
      rules: checked ? checked.toString() : '',
    });
    createMessage.success('保存成功');
  } finally {
    changeLoading(false);
  }
}
</script>
